<template>
  <div class="content">
    <div class="pageTableView" style="margin-top: 0">
      <div class="pageTableMenuView">
        <div class="pageTableTitle"> 订单统计</div>
      </div>
      <el-row style="width:100%;padding: 0">
        <el-col :span="8">
          <div class="numberDiv">订单总数： <span class="numberSpan"> {{ totalCount || '--' }} </span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="numberDiv">待派工工序订单： <span class="numberSpan"> {{ offDutyCount || '--' }} </span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="numberDiv">已派工工序订单： <span class="numberSpan">{{ sentCount || '--' }} </span></div>
        </el-col>
      </el-row>
    </div>
    <div class="pageTableView">
      <div style="display: flex;width: 100%;justify-content: space-between">
        <el-tabs v-model="isWorkStatusTab" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="待派工" name="0"></el-tab-pane>
          <el-tab-pane label="已派工" name="1"></el-tab-pane>
          <el-tab-pane label="已完结" name="2"></el-tab-pane>
        </el-tabs>

        <div>
          <el-button @click="endClick" type="danger" :icon="SwitchButton"
                     :disabled="multipleSelection.length == 0"
                     class="endButton"
          >批量强制完结
          </el-button>
          <el-button type="primary" @click="handleDeleteBatch"
                     :disabled="multipleSelection.length == 0">批量下发
          </el-button>
          <el-button type="primary" @click="printClick"
                     :disabled="multipleFatherSelection.length == 0">打印
          </el-button>
        </div>
      </div>
      <div>
        <div class="boxSel">
          <SearchForm v-model="searchParamTwo" :fields="searchFields" :handleSearch="handleSearchTwo"/>
        </div>
      </div>
      <el-table ref="table" :data="list" style="width: 100%" height="calc(100vh - 420px)" row-key="id" border :expand-row-keys="expandedRows"
                @expand-change="handleExpandChange">
        <el-table-column width="45" align="center">
          <template #default="scopes">
            <el-checkbox @change="handleSelectionFatherChange(scopes.row)"/>
          </template>
        </el-table-column>
        <el-table-column type="expand">
          <template #default="scope">
            <!--            子级列表-->
            <div m="4">
              <el-table :ref="'tableCil' + scope.$index" :stripe="false" border size="small"
                        :data="scope.row.children" style="width: 83vw;margin-left: 20px"
                        header-cell-class-name="blueTableHeader">
                <!-- <el-table-column type="selection" width="45" align="center" > -->
                <!-- @selection-change="handleSelectionChange" -->
                <!-- </el-table-column> -->
                <el-table-column width="45" align="center">
                  <template #default="scopes">
                    <el-checkbox @change="handleSelectionChange(scopes.row)"/>
                  </template>
                </el-table-column>
                <el-table-column type="index" width="80" label="序号" align="center"/>
                <el-table-column prop="workNo" label="工单号" align="center"></el-table-column>
                <el-table-column prop="productName" label="产品名称" align="center"></el-table-column>
                <el-table-column prop="equipmentName" label="设备名称" align="center"></el-table-column>
                <el-table-column prop="equipmentCode" label="设备编码" align="center"></el-table-column>
                <el-table-column prop="orderCount" label="工单数量" align="center"></el-table-column>
                <el-table-column prop="daySendWorkNumber" label="每日派工数量" align="center"></el-table-column>
                <el-table-column prop="alreadyCount" label="报工数量" align="center"></el-table-column>
                <el-table-column label="状态" align="center">
                  <template #default="{ row }"> {{ dicData.find(i => i.value === row.status)?.label }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right" width="180">
                  <template #default="scopeq">
                    <el-button size="small" :icon="Edit"
                               @click="handleDeleteRow(scopeq.row, true, scope.row)" :disabled="scopeq.row.status > 2">
                      下发
                    </el-button>
                    <el-button size="small" type="danger" :icon="Delete" :disabled="scopeq.row.status != 0"
                               @click="handleDeleteRow(scopeq.row,false,scope.row)">删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" width="60" label="序号" align="center"/>
        <el-table-column label="工序订单号" prop="no" width="200" show-overflow-tooltip sortable align="center"/>
        <el-table-column label="工序名称" prop="procedureName" width="250" show-overflow-tooltip sortable align="center"/>
        <el-table-column label="产品名称" prop="productName" width="200" show-overflow-tooltip sortable align="center"/>
        <el-table-column label="产出物料编码" prop="outMaterialNo" width="200" show-overflow-tooltip sortable align="center"/>
        <el-table-column label="计划属性" prop="outMaterialNo" width="200" show-overflow-tooltip sortable align="center">
          <template #default="scope">
            <span v-if="scope.row.property == 1">返工</span>
            <span v-else>正常</span>
          </template>
        </el-table-column>
        <el-table-column label="订单数量" prop="orderCount" width="150" show-overflow-tooltip sortable align="center"/>
        <el-table-column label="已报工数量" prop="alreadyCount" width="150" show-overflow-tooltip sortable align="center"/>
        <el-table-column prop="previousCompletionCount" label="上道工序生产数量" align="center" sortable min-width='200'/>
        <el-table-column prop="transfersNumber" label="上道工序已调拨数量" align="center" sortable min-width='200'/>
        <el-table-column label="计划状态" prop="status" width="150" show-overflow-tooltip sortable align="center">
          <template #default="scope">
            <span>{{ statusData.find(i => i.value === scope.row.status)?.label }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="organizationOrgName" label="车间名称" sortable width="200" align="center"/>
        <el-table-column prop="planBeginTime" label="计划开始时间" sortable width="200" align="center"/>
        <el-table-column prop="planEndTime" label="计划结束时间" sortable width="200" align="center"/>
        <el-table-column prop="updateUserName" label="更新人" sortable width="200" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" sortable width="200" align="center"/>
        <el-table-column label="操作" :width="isWorkStatus != 2 ? 380 : 200" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" text type="warning" :icon='Discount' class="operationBtn" v-if="isWorkStatus != 2"
                       @click="handleEditRow(scope.row)">生成领料单
            </el-button>
            <el-button size="small" type="text" :icon='Discount' class="operationBtn" v-if="isWorkStatus != 2"
                       @click="handleBatchAdd(scope.row)">批量派工
            </el-button>
            <el-button size="small" text :icon='Operation' class="operationBtn"
                       @click="handleEditRow(scope.row, 'detail')">详情
            </el-button>
            <el-button type="danger" plain text size="small" @click="handleOver(scope.row)" v-if="isWorkStatus != 2"
                       :icon="SwitchButton">完结
            </el-button>
            <el-button type="danger" plain text size="small" icon="Refresh" @click="handleUnOver(scope.row)" v-else
            >重新打开
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background layout="total,sizes,  prev, pager, next" :total="total"
                       :page-sizes="[10, 20, 50, 100, 200, 500]" :current-page="params.current"
                       :page-size="params.pageSize" @current-change="handlePageChangeTrue"
                       @size-change="handleSizeChange"/>
      </div>
    </div>
    <el-dialog :model-value="deleteShow" title="删除" class="modal-title-layout" @close="deleteShow = false">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span></span>
      </p>
      <template #footer>
        <el-button type="default" @click="deleteShow = false">取消</el-button>
        <el-button type="primary" @click="handleDeleteSure">确定</el-button>
      </template>
    </el-dialog>
    <ModalOpen :visible="createStatus" :form="form" :handleAddSubmit="handleAddSubmit" :material="material"
               :handleClose="handleClose"/>
    <CreateOrUpdateModal :visible="batchStatus" :form="batchForm" title="批量派工"
                         @update:visible="createStatus = $event" :handleAddSubmit="handleBatchSubmit"
                         :materialList="materialList"
                         :putMaterialData="putMaterialData" :equipmentData="equipmentData" :titleDetail="titleDetail"
                         :handleClose="handleBatchClose" @update:putMaterialData="putMaterialData = $event"/>
  </div>
</template>
<script lang="ts" setup>
import {computed, getCurrentInstance, onMounted, ref} from 'vue';
import SearchForm from '@/components/SearchForm.vue';
import type {TabsPaneContext} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import {useRouter} from 'vue-router';
import {Delete, Discount, Edit, Operation, SwitchButton} from '@element-plus/icons-vue';

import ModalOpen from './modaOpen.vue';
import {
  basedataWorkOrderUpdate,
  delProcedureOrderApi,
  procedureOrderDataApi,
  productAllApi,
  putMaterialRedord
} from '@/api/scheduling/dispatchManagement';
import axiosInstance from '@/utils/http/api';
import CreateOrUpdateModal from '../dispatchManagementDetail/modalOpen.vue';

const router = useRouter();
const table = ref(null);
const params = ref({
  pageSize: 10,
  current: 1
});
const statusData = ref([
  {label: '新建', value: 0},
  {label: '执行中', value: 1},
  {label: '完成', value: 2}
]);

const searchFields = ref([
  {
    name: 'procedureName',
    label: '工序名称',
    component: 'input',
    placeholder: '',
    class: '!w-[350px]'
  }, {
    name: 'no',
    label: '工序订单号',
    component: 'input',
    placeholder: '',
    class: '!w-[350px]'
  }, {
    name: 'productName',
    label: '产品名称',
    component: 'input',
    placeholder: '',
    class: '!w-[350px]'
  }, {
    name: 'outMaterialNo',
    label: '产出物料编码',
    component: 'input',
    placeholder: '',
    class: '!w-[350px]'
  }
]);
const callParams = ref({
  pageSize: 10,
  current: 1
});

const sentCount = ref(0);
const offDutyCount = ref(0);
const totalCount = ref(0);
const total = ref(0);
const callList = ref([]);
const list = ref([]);
const tableHeight = computed(() => window.innerHeight - 200);

const productData = ref([]);

const deleteShow = ref(false);
const deleteRow = ref(null);

const createStatus = ref(false);
const form = ref({});
const material = ref([]);
const searchParam = ref({});
const searchParamTwo = ref({});
const handleClose = () => {
  createStatus.value = false;
  material.value = [];
};
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  if (multipleSelection.value.includes(val)) {
    // 如果 multipleSelection 已经包含 val，则删除它
    multipleSelection.value = multipleSelection.value.filter(item => item !== val);
  } else {
    // 如果 multipleSelection 不包含 val，则添加它
    multipleSelection.value.push(val);
  }
};

const multipleFatherSelection = ref([]);

const handleSelectionFatherChange = (val) => {
  if (multipleFatherSelection.value.includes(val)) {
    // 如果 multipleSelection 已经包含 val，则删除它
    multipleFatherSelection.value = multipleFatherSelection.value.filter(item => item !== val);
  } else {
    // 如果 multipleSelection 不包含 val，则添加它
    multipleFatherSelection.value.push(val);
  }
};

const {proxy}: any = getCurrentInstance();
// 打印
const printClick = () => {
  const templateName = 'test_print1/WorkOrderPlanReport2.cpt';
  const list = [];
  for (const item of multipleFatherSelection.value) {
    if (!item.workOrderIds || item.workOrderIds.length == 0) {
      ElMessage.error(item.no + '没有工单数据可打印');
      return false;
    } else {
      for (const items of item.workOrderIds) {
        list.push({id: items});
      }
    }
  }
  if (list.length > 0) {
    proxy.$printClick(templateName, list);
  }
};

const handleBatchClose = () => {
  batchStatus.value = false;
};
const handleSearchTwo = () => {
  multipleSelection.value = [];
  multipleFatherSelection.value = [];
  getCallListTrue();
};
const handleSearch = () => {
  multipleSelection.value = [];
  multipleFatherSelection.value = [];
  getCallList();
};

const dicData = ref([
  {label: '新建', value: 0},
  {label: '待排产', value: 1},
  {label: '已排产', value: 2},
  {label: '下发', value: 3},
  {label: '开工', value: 4},
  {label: '中断', value: 5},
  {label: '暂停', value: 6},
  {label: '完成', value: 7}
]);

const isWorkStatusTab = ref('0');
const isWorkStatus = ref('0');
const handleClick = (tab: TabsPaneContext, event: Event) => {
  isWorkStatus.value = tab.paneName;
  multipleSelection.value = [];
  multipleFatherSelection.value = [];
  getCallListTrue();
};


const handleExpandChange = (row: any, expandedRowsArr: any[]) => {
  // 仅同步当前操作行的展开状态
  if (expandedRowsArr.length > 0) {
    // 展开时添加当前行ID
    expandedRows.value = [...expandedRows.value, row.id];
    rowChildren(row);
  } else {
    // 收起时移除当前行ID
    expandedRows.value = expandedRows.value.filter(id => id !== row.id);
  }
};

const rowChildren = (row: any) => {
  axiosInstance.post('/api/planProcedureOrder/procedureOrderQueryprocedure', {id: row.id}).then(res => {
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return false;
    }
    const listGroup = list.value.map((item) => {
      if (item.id == row.id) {
        return {...item, children: res.data};
      }
      return item;
    });
    console.log(listGroup, 'listGrouplistGroup');
    list.value = listGroup;

    callList.value = callList.value.map((item) => {
      if (item.id == row.id) {
        return {...item, children: res.data};
      }
      return item;
    });
  });
};


const getProducts = async () => {
  const res = await productAllApi();
  productData.value = res.data;
};

const getCallList = async () => {
  const res = await procedureOrderDataApi({...callParams.value, status: isWorkStatus.value, ...searchParam.value});
  callList.value = res.data.records;
};

// 在script部分增加expandedRows响应式变量
const expandedRows = ref<string[]>([]); // 存储当前展开的行keys

// 修改getCallListTrue方法
const getCallListTrue = async () => {
  multipleSelection.value = [];
  const res = await procedureOrderDataApi({...params.value, status: isWorkStatus.value, ...searchParamTwo.value});

  list.value = res.data.records;
  total.value = res.data.total;

  // 清空展开状态
  expandedRows.value = [];
};

const handleBatchSubmit = () => {
  let number = 0;
  const promises = [];
  for (const item of putMaterialData.value) {
    promises.push({
      equipmentId: item.equipmentId,
      orderCount: item.needNumber,
      procedureOrderId: rowInfo.value.id,
      toolingId: item.toolId,
      daySendWorkNumber: item.daySendWorkNumber
      // toolRegisterId:item.toolRegisterId
    });
    number = number + item.needNumber;
  }

  if (Number(number) > Number(titleDetail.value.orderCount)) {
    ElMessage.warning('已超出待派发数量');
    return false;
  }
// 修改 putMaterialRedord 的成功回调部分
  putMaterialRedord(promises).then(res => {
    if (res.code === 200) {
      // 仅展开当前操作的行
      const currentRowId = rowInfo.value.id;
      expandedRows.value = [currentRowId]; // 只保留当前行的ID

      // 刷新子表数据
      rowChildren(rowInfo.value);

      batchStatus.value = false;
      ElMessage.success('保存成功');
    } else {
      ElMessage.error(res.message);
    }
  });
};

const handleAddSubmit = (data) => {
  axiosInstance.post('/api/planProcedureOrder/queryIsFirst', {id: form.value.id})
      .then((resq) => {
        const loop = JSON.parse(JSON.stringify(data));
        const params = {
          isFirst: resq.data,
          // materialName: data[0].materialName,
          // materialType: data[0].materialType,
          // numPutCompare: data[0].numPutCompare,
          // storageName: data[0].storageName,
          // id: form.value.id,
          // currenNaterialCount: Number(data[0].needNumber),
          // count: '1',
          // procedureCount: 130,
          // alreadyMaterialCount: 130,
          // planCount: 130,
          procedureOrderId: form.value.id,
          details: [],
          targetStorageId: data[0].storageId
        };

        for (const item of loop) {
          item.materialCount = item.currenNaterialCount;
          item.targetStorageId = item.storageId;
          item.procedureOrderId = form.value.id;
        }
        params.details = loop;

        axiosInstance.post('/api/warehouseMaterialTransferOrder/save', {
          ...params, ...{
            transferType: 'pick',
            businessType: 7
          }
        })
            .then((res) => {
              if (res.code !== 200) {
                ElMessage.error(res.message);
                return false;
              }
              if (res.code === 200) {
                ElMessage.success('领取成功');
                createStatus.value = false;
                getCallList();
              } else {
                ElMessage.error('领取失败，请检查参数');
              }
            });
      });
  return;


  // materialTransferOrderApi(params).then((res) => {
  //   if (res.code === 200) {
  //     ElMessage.success("领取成功");
  //     createStatus.value = false;
  //     getCallList();
  //   } else {
  //     ElMessage.error("领取失败，请检查参数");
  //   }
  // });

};

const endClick = async () => {
  ElMessageBox.confirm('是否强制完结?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
      .then(() => {
        const promises = multipleSelection.value.map((item) => {
          return new Promise((resolve, reject) => {
            axiosInstance.post('/api/workOrder/constraintEnd', {
              id: item.id // 假设每个对象都有一个 id 属性
            })
                .then((res) => {
                  if (res.code === 200) {
                    resolve(res);
                  } else {
                    reject(res);
                  }
                })
                .catch((error) => {
                  reject(error);
                });
          });
        });

        Promise.all(promises)
            .then(() => {
              ElMessage.success('所有强制完结操作已完成');
              getList();
            })
            .catch((error) => {
              ElMessage.error('强制完结操作失败');
            });
      })
      .catch(() => {
        ElMessage.info('用户取消操作');
      });
};


const handleOver = (row: any) => {
  ElMessageBox.confirm('确定完结该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.post('/api/planOrder/updateByIdStatus', {id: row.id, status: '2'})
        .then(res => {
          if (res.code === 200) {
            ElMessage.success('操作成功');
            getCallList();
            getCallListTrue();
          } else {
            ElMessage.error(res.message);
          }
        });
  }).catch(() => {
  });
};

const handleUnOver = (row: any) => {
  ElMessageBox.confirm('确定重新打开该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.put('/api/planProcedureOrder/update', {id: row.id, status: '1'})
        .then(res => {
          if (res.code === 200) {
            ElMessage.success('操作成功');
            getCallList();
            getCallListTrue();
          } else {
            ElMessage.error(res.message);
          }
        });
  }).catch(() => {
  });
};


const currentItem = ref({});

const handleDeleteBatch = () => {
  ElMessageBox.confirm('是否确认批量下发？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  }).then(async () => {
    const param = [];
    for (const item of multipleSelection.value) {
      param.push({id: item.id, status: 3, equipmentId: item.equipmentId});
    }
    basedataWorkOrderUpdate(param).then(res => {
      if (res.code === 200) {
        ElMessage.success('下发成功');
        list.value = [];
        getList();
        return false;
      }
      ElMessage.error(res.message);
    });
  });
};

const handleDeleteRow = (row, flag, fLine) => {
  if (flag) {
    ElMessageBox.confirm('是否确认下发？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }).then(async () => {
      currentItem.value = {...row, open: flag};
      basedataWorkOrderUpdate([{id: row.id, status: 3, equipmentId: row.equipmentId}]).then(res => {
        if (res.code === 200) {
          ElMessage.success('下发成功');
          handleExpandChange(fLine, list.value);
          return false;
        }
        ElMessage.error(res.message);
      });
    }).catch(() => {
    });
    return;
  }
  ElMessageBox.confirm('是否要删除？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    currentItem.value = {...row, open: flag};
    await handleDeleteSure(fLine);
  }).catch(() => {
  });

};


const handleDeleteSure = async () => {
  try {
    await delProcedureOrderApi({ids: [currentItem.value.id]});
    deleteShow.value = false;
    getCallList();
  } catch (error) {
    console.error(error);
  }
};

const handleEditRow = (row: any, type?: string) => {
  if (type === 'detail') {
    // 显示详情页面或弹窗
    router.push(`/scheduling/dispatchManagementDetail?id=${row.id}`);
  } else {
    // 生成领料单逻辑
    // 示例：调用生成领料单的 API
    generateMaterialOrder(row);
  }
};


const putMaterialData = ref([]);
const batchForm = ref({});
const batchStatus = ref(false);
const materialList = ref([]);
const equipmentData = ref([]);
const titleDetail = ref({});
const rowInfo = ref({});
const handleBatchAdd = (e) => {
  rowInfo.value = e;
  putMaterialData.value = [{
    needNumber: 0,
    equipmentId: '',
    toolId: ''
  }];
  axiosInstance.post('/api/planProcedureOrder/queryById', {id: e.id})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        titleDetail.value = res.data;
        batchForm.value = {};
        batchStatus.value = true;
      });

};

const generateMaterialOrder = async (row: any) => {
  axiosInstance.post('/api/planProcedureOrder/getMaterialRequisition', {
    id: row.id
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        material.value = res.data;
        form.value = {...row, ...res.data};
        createStatus.value = true;
      });
  // procedureResourceApi({ procedureId: row.procedureId }).then((res) => {
  //   if (res.code === 200) {
  //     if (res.data.records.length) {
  //       const { configJson } = res.data.records[0];
  //       const putMaterial = JSON.parse(configJson).storage[0];
  //       material.value = putMaterial.IntMaterial.map((item) => ({
  //         ...putMaterial,
  //         putMaterialId: item.MaterialId,
  //         numPutCompare: putMaterial.outMaterial ? Number(putMaterial.outMaterial[0].numPutCompare) : 0,
  //         needNumber: Number(row.orderCount),
  //         outputNumber: Number(putMaterial.numPutCompare) * Number(row.orderCount) || 0,
  //       }));
  //     }
  //     form.value = { ...row };
  //     createStatus.value = true;
  //   }
  // });
};

// 分页处理
const handleSizeChange = (currentPage: number) => {
  params.value.pageSize = currentPage;
  getCallListTrue();
};

const handlePageChangeTrue = (currentPage: number) => {
  params.value.current = currentPage;
  getCallListTrue();
};

const getList = () => {
  getProducts();
  // getCallList();
  getCallListTrue();
};

const getNumber = () => {
  axiosInstance.get('/api/planProcedureOrder/queryCount', {})
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        sentCount.value = res.data.sentCount;
        offDutyCount.value = res.data.offDutyCount;
        totalCount.value = res.data.totalCount;
      });
};

// 其他方法和初始化逻辑
onMounted(() => {
  getList();
  getNumber();
});
</script>
<style scoped lang="scss">
.alignCenter {
  display: flex;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
  margin-bottom: 10px
}

.tableContent {
  background: #fff;
  padding-bottom: 10px;
}

.numberDiv {
  display: flex;
  align-items: center;
  color: #777;
}

.numberSpan {
  font-size: 25px;
  font-weight: 500;
  color: #333;
}

.boxSel {
  display: flex;
  justify-content: space-between
}
</style>
